<template>
  <div class="visit-page">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 姓名 -->
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="全部"></el-option>
            <el-option label="成功" value="成功"></el-option>
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="失败" value="失败"></el-option>
          </el-select>
        </el-form-item>

        <!-- 预约专家 -->
        <el-form-item label="预约专家">
          <el-input v-model="searchForm.expert" placeholder="请输入预约专家"></el-input>
        </el-form-item>

        <!-- 预约时间 -->
        <el-form-item label="预约时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" s :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表单 -->
    <el-table :data="tableData" style="width: 100%;" height="calc(100vh - 290px)" stripe border>
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="userName" label="姓名" />
      <el-table-column prop="userTel" label="联系方式" />
      <el-table-column prop="userSfz" label="身份证号" />
      <el-table-column prop="userUnite" label="单位" />
      <el-table-column prop="professorName" label="预约专家" />
      <el-table-column prop="appointmentContent" label="预约事项">
        <template #default="scope">
          <el-tooltip effect="light" :content="scope.row.appointmentContent" placement="top"
            :disabled="scope.row.appointmentContent.length <= 10">
            <div class="appointment-content">
              {{
                scope.row.appointmentContent.length > 10
                  ? scope.row.appointmentContent.slice(0, 10) + '...'
                  : scope.row.appointmentContent
              }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="申请时间" />
      <el-table-column prop="appointmentTime" label="预约时间" />

      <el-table-column prop="status" label="预约结果" width="100">
        <template #default="scope">
          <el-tag :type="getType(scope.row.status)">{{
            getResult(scope.row.status)
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" @click="handleDetail({ type: 'open', data: scope.row })">查看详情</el-button>
          <el-button v-if="scope.row.status === 0" type="text"
            @click="handleInspect({ type: 'open', data: scope.row })">审核</el-button>
          <el-button type="text" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination :total="pagination.total" :page-size.sync="pagination.pageSize"
      :current-page.sync="pagination.currentPage" @pagination-change="handlePaginationChange" />

    <!-- 查看详情 -->
    <AppointmentDialog :visible="dialogVisible.appointmentDialog" :form="appointmentForm" @handleDetail="handleDetail"
      :getType="getType" />

    <!-- 审核 -->
    <InspectDialog :visible="dialogVisible.inspectDialog" :form="inspectForm" @handleInspect="handleInspect" />
  </div>
</template>

<script>
import Pagination from "@/components/Pagination.vue";
import AppointmentDialog from "@/components/AppointmentDialog.vue";
import InspectDialog from "@/components/InspectDialog.vue"
import { pickerOptions } from "@/common/utils";
import { APPOINTMENT_STATUS, VISITOR_TABLE_DATA } from "@/common/constants.js";
import { deleteAppointment, updateAppointment, searchAppointmentList } from "@/api/visit.js"

export default {
  components: {
    Pagination,
    AppointmentDialog,
    InspectDialog,
  },

  data() {
    return {
      /**
       * 日期选项
       * @type {Object}
       */
      pickerOptions: pickerOptions,

      /**
       * 表格数据
       * @type {Array}
       */
      tableData: VISITOR_TABLE_DATA,

      /**
       * 分页信息
       * @type {Object}
       */
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 200,
      },

      /**
       * 搜索栏数据
       * @type {Object}
       */
      searchForm: {
        name: "",
        status: "全部",
        expert: "",
        dateRange: [],
      },

      /**
       * 详情dialog数据
       * @type {Object}
       */
      appointmentForm: {
        userName: "",
        userTel: "",
        appointmentTime: "",
        userUnite: "",
        professorName: "",
        appointmentContent: "",
        createTime: "",
        updateTime: "",
        status: ""
      },

      /**
       * 审核dialog数据
       * @type {Object}
       */
      inspectForm: {
      },

      /**
       * dialog状态数据
       */
      dialogVisible: {
        appointmentDialog: false,
        inspectDialog: false,
      }

    };
  },
  async mounted() {
    await this.handleSearch();
  },
  methods: {
    /**
     * 查询
     * @returns {void}
     */
    async handleSearch() {
      try {
        this.$loading({ lock: true, text: "正在查询，请稍后..." });

        // 调用查询接口
        const response = await searchAppointmentList(this.searchForm, this.pagination);

        // 更新表格数据和分页信息
        if (response.success) {
          this.tableData = response.data;
          this.pagination.total = this.tableData.length;
        } else {
          this.$message.error(response.message || "查询失败");
        }
      } catch (error) {
        console.error("查询失败:", error);
        this.$message.error(error.message || "查询失败");
      } finally {
        this.$loading().close();
      }
    },

    /**
     * 重置查询
     * @returns {void}
     */
    resetSearch() {
      this.searchForm = {
        name: "",
        status: "全部",
        expert: "",
        dateRange: [],
      };
    },

    /**
     * 获取预约结果类型
     * @param {Number} status 0：审核中，1:失败，2：成功
     * @returns {String}
     */
    getType(status) {
      switch (status) {
        case APPOINTMENT_STATUS["成功"]:
          return "success";
        case APPOINTMENT_STATUS["失败"]:
          return "danger";
        case APPOINTMENT_STATUS["审核中"]:
          return "warning";
        default:
          return "";
      }
    },

    /**
     * 获取预约结果
     * @param {Number} 0：审核中，1:失败，2：成功
     * @returns {String}
     */
    getResult(status) {
      switch (status) {
        case APPOINTMENT_STATUS["成功"]:
          return "成功";
        case APPOINTMENT_STATUS["失败"]:
          return "失败";
        case APPOINTMENT_STATUS["审核中"]:
          return "审核中";
        default:
          return "";
      }
    },

    /**
     * 查看详情
     * @param {String} type - cancel or open
     * @param {Object} data
     * @returns {void}
     */
    handleDetail({ type, data }) {
      if (type === "open") {
        const keys = Object.keys(this.appointmentForm);
        keys.map((k) => this.appointmentForm[k] = data[k])
        this.dialogVisible.appointmentDialog = true;
      } else if (type === "cancel") {
        this.dialogVisible.appointmentDialog = false;
      }
    },

    /**
     * 审核
     * @param type - save or cancel or open
     * @param {Object} data - 记录数据
     * @returns {void}
     */
    async handleInspect({ type, data }) {
      if (type === "open") {
        this.inspectForm = { ...data };
        if (data.status === APPOINTMENT_STATUS["审核中"]) {
          this.inspectForm.status = APPOINTMENT_STATUS["失败"];
        }
        this.dialogVisible.inspectDialog = true;
      } else if (type === "cancel") {
        this.dialogVisible.inspectDialog = false;
      } else if (type === "save") {
        try {
          // 调用更新接口
          const response = await updateAppointment(data, this.tableData);

          if (response.success) {
            // 更新表格数据
            this.tableData = response.data;
            this.pagination.total = this.tableData.length;

            this.$message.success('审核完成');
          } else {
            this.$message.error('审核失败');
          }
        } catch (error) {
          if (error !== 'cancel') {
            this.$message.error(error.message || '审核失败');
          }
        }
        this.dialogVisible.inspectDialog = false;
      }
    },

    /**
     * 删除记录
     * @param {Object} scope - 记录数据
     * @returns {void}
     */
    async handleDelete(row, index) {
      index += 1;
      try {
        // 确认删除
        await this.$confirm(`确定删除第${index}条， ${row.userName} 的访客申请记录吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        // 调用删除接口
        const response = await deleteAppointment(row.id, this.tableData);

        if (response.success) {
          // 更新表格数据
          this.tableData = response.data;
          this.pagination.total = this.tableData.length;

          this.$message.success('删除访客申请记录成功');
        } else {
          this.$message.error('删除访客申请记录失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '删除访客申请记录失败');
        }
      }
    },

    /**
     * 处理页面切换
     * @param param0 获取分页信息
     * @returns {void}
     */
    handlePaginationChange({ currentPage, pageSize }) {
      this.pagination.currentPage = currentPage;
      this.pagination.pageSize = pageSize;
      this.fetchData();
    },
  },
};
</script>

<style lang="scss" scoped>
@import url('@/assets/scss/form.scss');
</style>
